package com.example.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @ClassName LoginController
 * @Description TODO 登录相关的控制器
 * @Version 1.0
 */
@Controller
public class LoginController {
    @GetMapping("/toLogin")
    public String loginPage() {
        return "redirect:/login?error=true";
    }

    @PostMapping("/login")
    public String login(@RequestParam String loginName,
                        @RequestParam String password) {
        // 1. 获取当前 Subject
        Subject currentUser = SecurityUtils.getSubject();

        // 2. 判断用户是否已经认证（登录）
        if (!currentUser.isAuthenticated()) {
            // 3. 将用户名和密码封装成 UsernamePasswordToken
            UsernamePasswordToken token = new UsernamePasswordToken(loginName, password);
            token.setRememberMe(true); // 可选：记住我功能

            try {
                // 4. 执行登录，这会委托给 Realm 的 doGetAuthenticationInfo 方法
                currentUser.login(token);
                // 登录成功，重定向到首页或目标页
                return "redirect:/index.html";
            } catch (UnknownAccountException uae) {
                // 用户名不存在
                System.out.println("用户名不存在: " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
                // 密码不正确
                System.out.println("密码不正确 for: " + token.getPrincipal());
            } catch (AuthenticationException ae) {
                // 其他认证异常
                System.out.println("认证失败: " + ae.getMessage());
            }
        }
        // 登录失败，返回登录页
        return "redirect:/login?error=true";
    }
    /*
     * @Description //TODO 登出
     * @Params []
     * @return java.lang.String
     * @version 1.0
     **/
    @GetMapping("/logout")
    public String logout() {
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout(); // Shiro 会清除 Session 和身份信息
        return "redirect:/login";
    }
}
